package com.example.xposedtest.ui;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.xposedtest.R;
import com.example.xposedtest.utils.StepConfigUtils;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    // 配置键名
    public static final String PREFS_NAME = "XposedPrefs";
    public static final String PREF_FAKE_STEP_ENABLED = "fake_step_enabled";
    public static final String PREF_STEP_VALUE = "step_value";
    private static final String PREF_AUTO_REPLY = "auto_reply_enabled";
    private static final String PREF_REPLY_TYPE = "reply_type"; // 0:DeepSeek 1:自定义文本 2:图片 3:视频
    private static final String PREF_CUSTOM_TEXT = "custom_text";
    private static final String PREF_IMAGE_PATH = "image_path";
    private static final String PREF_VIDEO_PATH = "video_path";

    // 权限请求码
    private static final int REQUEST_MEDIA_PERMISSION = 1001;
    private static final int REQUEST_SELECT_IMAGE = 1002;
    private static final int REQUEST_SELECT_VIDEO = 1003;

    // 控件
    private Switch autoReplySwitch;
    private Spinner replyTypeSpinner;
    private LinearLayout customTextLayout, imageLayout, videoLayout;
    private EditText customTextEdit;
    private Button selectImageBtn, selectVideoBtn;
    private TextView imagePathTv, videoPathTv, statusText;
    private SharedPreferences prefs;
    private SwitchCompat stepSwitch;
    private EditText stepEdit;
    private Button stepSaveBtn;
    private SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化SharedPreferences（兼容Xposed读取）
        prefs = getSharedPreferences(PREFS_NAME, Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? MODE_WORLD_READABLE : MODE_PRIVATE);

        // 绑定控件
        initViews();

        // 加载保存的配置
        loadSavedConfig();

        // 加载步数配置
        loadStepConfig();

        // 权限检查
        checkMediaPermission();

        // 监听总开关
        autoReplySwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            prefs.edit().putBoolean(PREF_AUTO_REPLY, isChecked).apply();
            updateStatusText();
        });

        // 监听回复类型切换（动态显示对应控件）
        replyTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 保存回复类型
                prefs.edit().putInt(PREF_REPLY_TYPE, position).apply();
                // 显示对应控件
                switch (position) {
                    case 0: // DeepSeek
                        hideAllTypeLayouts();
                        break;
                    case 1: // 自定义文本
                        hideAllTypeLayouts();
                        customTextLayout.setVisibility(View.VISIBLE);
                        break;
                    case 2: // 图片
                        hideAllTypeLayouts();
                        imageLayout.setVisibility(View.VISIBLE);
                        break;
                    case 3: // 视频
                        hideAllTypeLayouts();
                        videoLayout.setVisibility(View.VISIBLE);
                        break;
                }
                updateStatusText();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        // 监听自定义文本输入（实时保存）
        customTextEdit.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(android.text.Editable s) {
                prefs.edit().putString(PREF_CUSTOM_TEXT, s.toString()).apply();
            }
        });

        // 监听图片选择
        selectImageBtn.setOnClickListener(v -> {
            if (checkMediaPermission()) {
                openImageSelector();
            }
        });

        // 监听视频选择
        selectVideoBtn.setOnClickListener(v -> {
            if (checkMediaPermission()) {
                openVideoSelector();
            }
        });

        // 步数配置逻辑
        stepSaveBtn.setOnClickListener(v -> saveStepConfig());
    }

    // 初始化控件
    private void initViews() {
        autoReplySwitch = findViewById(R.id.auto_reply_switch);
        replyTypeSpinner = findViewById(R.id.reply_type_spinner);
        customTextLayout = findViewById(R.id.custom_text_layout);
        imageLayout = findViewById(R.id.image_layout);
        videoLayout = findViewById(R.id.video_layout);
        customTextEdit = findViewById(R.id.custom_text_edit);
        selectImageBtn = findViewById(R.id.select_image_btn);
        selectVideoBtn = findViewById(R.id.select_video_btn);
        imagePathTv = findViewById(R.id.image_path_tv);
        videoPathTv = findViewById(R.id.video_path_tv);
        statusText = findViewById(R.id.status_text);
        stepSwitch = findViewById(R.id.step_switch);
        stepEdit = findViewById(R.id.step_edit);
        stepSaveBtn = findViewById(R.id.step_save_btn);
    }

    // 加载步数配置
    private void loadStepConfig() {
        boolean isEnabled = prefs.getBoolean(PREF_FAKE_STEP_ENABLED, false);
        int stepValue = prefs.getInt(PREF_STEP_VALUE, 10000);

        stepSwitch.setChecked(isEnabled);
        stepEdit.setText(String.valueOf(stepValue));
    }

    // MainActivity.java 中添加步数保存逻辑
    private void saveStepConfig() {
        boolean isEnabled = stepSwitch.isChecked();
        String stepStr = stepEdit.getText().toString().trim();
        int stepValue = 10000;

        if (!stepStr.isEmpty()) {
            try {
                stepValue = Integer.parseInt(stepStr);
                if (stepValue <= 0) {
                    Toast.makeText(this, "请输入大于0的整数", Toast.LENGTH_SHORT).show();
                    return;
                }
            } catch (NumberFormatException e) {
                Toast.makeText(this, "请输入有效的整数", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        // 保存到外部文件（不依赖上下文）
        StepConfigUtils.saveConfig(isEnabled, stepValue);
        Toast.makeText(this, "步数配置已保存", Toast.LENGTH_SHORT).show();
    }

    // 加载保存的配置
    private void loadSavedConfig() {
        boolean isAutoReplyEnabled = prefs.getBoolean(PREF_AUTO_REPLY, false);
        int replyType = prefs.getInt(PREF_REPLY_TYPE, 0);
        String customText = prefs.getString(PREF_CUSTOM_TEXT, "");
        String imagePath = prefs.getString(PREF_IMAGE_PATH, "");
        String videoPath = prefs.getString(PREF_VIDEO_PATH, "");

        // 赋值给控件
        autoReplySwitch.setChecked(isAutoReplyEnabled);
        replyTypeSpinner.setSelection(replyType);
        customTextEdit.setText(customText);
        imagePathTv.setText(imagePath.isEmpty() ? "未选择图片" : imagePath);
        videoPathTv.setText(videoPath.isEmpty() ? "未选择视频" : videoPath);

        // 初始显示对应控件
        switch (replyType) {
            case 1: customTextLayout.setVisibility(View.VISIBLE); break;
            case 2: imageLayout.setVisibility(View.VISIBLE); break;
            case 3: videoLayout.setVisibility(View.VISIBLE); break;
        }

        updateStatusText();
    }

    // 隐藏所有类型专属控件
    private void hideAllTypeLayouts() {
        customTextLayout.setVisibility(View.GONE);
        imageLayout.setVisibility(View.GONE);
        videoLayout.setVisibility(View.GONE);
    }

    // 更新状态文本
    private void updateStatusText() {
        boolean isEnabled = prefs.getBoolean(PREF_AUTO_REPLY, false);
        int replyType = prefs.getInt(PREF_REPLY_TYPE, 0);
        String typeStr = getResources().getStringArray(R.array.reply_types)[replyType];

        if (isEnabled) {
            statusText.setText(String.format("状态: 已激活 - 当前回复类型：%s", typeStr));
        } else {
            statusText.setText("状态: 已关闭 - 开启后将按选择类型自动回复");
        }
    }

    // 检查媒体文件权限
    private boolean checkMediaPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+：分别请求图片、视频权限
            boolean hasImagePerm = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED;
            boolean hasVideoPerm = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_VIDEO) == PackageManager.PERMISSION_GRANTED;
            if (!hasImagePerm || !hasVideoPerm) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO},
                        REQUEST_MEDIA_PERMISSION);
                return false;
            }
        } else {
            // Android 12及以下：请求外部存储权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_MEDIA_PERMISSION);
                return false;
            }
        }
        return true;
    }

    // 打开图片选择器
    private void openImageSelector() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_SELECT_IMAGE);
    }

    // 打开视频选择器
    private void openVideoSelector() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        intent.setType("video/*");
        startActivityForResult(intent, REQUEST_SELECT_VIDEO);
    }

    // 处理文件选择结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) return;

        Uri uri = data.getData();
        String filePath = getRealPathFromUri(uri); // 转换Uri为真实路径
        if (filePath == null || !new File(filePath).exists()) {
            Toast.makeText(this, "文件路径无效", Toast.LENGTH_SHORT).show();
            return;
        }

        // 保存路径并更新UI
        switch (requestCode) {
            case REQUEST_SELECT_IMAGE:
                prefs.edit().putString(PREF_IMAGE_PATH, filePath).apply();
                imagePathTv.setText(filePath);
                break;
            case REQUEST_SELECT_VIDEO:
                prefs.edit().putString(PREF_VIDEO_PATH, filePath).apply();
                videoPathTv.setText(filePath);
                break;
        }
    }

    // 权限请求结果回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_MEDIA_PERMISSION) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            if (!allGranted) {
                Toast.makeText(this, "需要媒体文件权限才能选择图片/视频", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 将Uri转换为真实文件路径（兼容多Android版本）
    private String getRealPathFromUri(Uri uri) {
        String path = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 4.4及以上：使用ContentResolver查询，移除try-with-resources
            android.content.ContentResolver resolver = getContentResolver();
            try {
                String[] projection = {MediaStore.Images.Media.DATA};
                android.database.Cursor cursor = resolver.query(uri, projection, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    path = cursor.getString(columnIndex);
                    cursor.close();
                }
            } catch (Exception e) {
                Log.e("MainActivity", "获取文件路径失败", e);
            }
        } else {
            // 4.4以下：直接获取路径
            path = uri.getPath();
        }
        return path;
    }
}